package tomasulo.component;

import tomasulo.Driver;
import tomasulo.unit.Instr;

public class Storer extends Component {

	private int addr = 0;
	private Register op1 = null;
	private static final int TIME_DELAY = 2;
	
	public Storer(String name) {
		super(name);
		op1 = new Register(name + "op1");
	}

	@Override
	public void afterTick(int tick) {
		if (busy) {
			if (time > 0) {
				--time;
				if (time == 0) {
					instr.setTimeComp(tick);
				}
			} else if (time == 0) {
				instr.setTimeWrite(tick);
				Driver.getMemory().setAt(addr, op1.getValue(), true);
				reset();
			}
		}
	}

	@Override
	public void checkCDB(int tick) {
		if (busy && (time == TIME_WAIT)) {
			op1.checkCDB(tick);		
			if (op1.isReady()) {
				time = TIME_DELAY;
			}
		}
	}

	@Override
	public boolean issue(Instr instr) {
		if (busy)
			return false;
		if (!instr.op.equals(Instr.OP.ST))
			return false;
		this.instr = instr;
		addr = instr.op1;
		op1.copyFromFU(instr.op0);
		busy = true;
		if (op1.isReady())
			time = TIME_DELAY;
		else
			time = TIME_WAIT; 
		return true;
	}
	
	public int getAddr() {
		return addr;
	}
	
	public Register getQ() {
		return op1;
	}

	@Override
	public void reset() {
		// TODO Auto-generated method stub
		busy = false;
		addr = 0;
		op1.setValue(0);
		time = 0;
	}

}
